﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Management.Automation;

using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.PowerShell;

namespace Mystery.SharePoint.PowerShell
{
	[Cmdlet("Set", "SPMBlobCache", SupportsShouldProcess = true)]
	[SPCmdlet(RequireUserFarmAdmin = true)]
	class SetBlobCacheCmdlet : SPSetCmdletBase<SPWebApplication>
	{
		/// <summary>
		/// The web application to modify
		/// </summary>
		[Parameter(Mandatory = true, ValueFromPipeline = true, Position = 0)]
		public SPWebApplicationPipeBind Identity { get; set; }
		/// <summary>
		/// The location to where the blob cache is located
		/// </summary>
		[Parameter(Mandatory = true)]
		public string Location { get; set; }
		/// <summary>
		/// Maximum sixe of cache
		/// </summary>
		[Parameter(Mandatory = true)]
		public int MaxSize { get; set; }
		/// <summary>
		/// extensions to include in cache
		/// </summary>
		[Parameter(Mandatory = false)]
		public string Path { get; set; }
		/// <summary>
		/// Indicates if the blob cache should be enabled or not
		/// </summary>
		[Parameter(Mandatory = false)]
		public SwitchParameter Enabled { get; set; }

		public SetBlobCacheCmdlet()
		{
			this.MaxSize = 10;
		}

		protected override void InternalValidate()
		{
			base.DataObject = this.Identity.Read();
		}
		protected override void UpdateDataObject()
		{
			WebConfigModifications modifications = new WebConfigModifications(base.DataObject, "BlobCache");

			base.Host.UI.WriteLine("Configuring Blob Cache");

			if (string.IsNullOrEmpty(this.Path) == false)
			{
				modifications.AddAttribute("path", "configuration/SharePoint/BlobCache", this.Path);
				base.Host.UI.WriteLine(string.Format(null, "Path: {0}", this.Path));
			}

			base.Host.UI.WriteLine(string.Format(null, "Location: {0}", this.Location));
			modifications.AddAttribute("location", "configuration/SharePoint/BlobCache", this.Location);
						
			base.Host.UI.WriteLine(string.Format(null, "Max Size: {0}", this.MaxSize));
			modifications.AddAttribute("maxSize", "configuration/SharePoint/BlobCache", this.MaxSize.ToString());

			base.Host.UI.WriteLine(string.Format(null, "Enabled: {0}", this.Enabled.IsPresent));
			modifications.AddAttribute("enabled", "configuration/SharePoint/BlobCache", XmlConvert.ToString(this.Enabled.IsPresent));

			modifications.Commit();
		}
	}
}
